import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_widgets/widgets/datePicker/kq_date_widget.dart';
import 'package:kq_flutter_widgets/widgets/datePicker/kq_datetime_widget.dart';
import 'package:kq_flutter_widgets/widgets/datePicker/kq_time_widget.dart';
import 'package:kq_flutter_widgets/widgets/selectTag/kq_select_tag.dart';

import '../../../resources/kq_theme_colors.dart';
import '../../../resources/l10n/kq_intl.dart';
import '../kq_botton_sheet_manger.dart';

/// 通用日期时间选择底部弹窗
///
/// @author 周卓
///
class KqDatePickerBottomSheet extends StatefulWidget {
  /// 能滚动到的最小日期
  final DateTime? minDateTime;

  /// 能滚动到的最大日期
  final DateTime? maxDateTime;

  /// 初始选择的时间。默认当前时间
  final DateTime? initialDateTime;

  /// 时间格式化的格式
  final String? dateFormat;

  /// 分钟间切换的差值
  final int minuteDivider;

  /// 左边按钮文字，默认“取消”
  final String? leftBtnText;

  /// 右边按钮文字，默认“确定”
  final String? rightBtnText;

  /// 时间选择组件显示的时间类型
  final KqDateTimePickerMode pickerMode;

  /// 时间选择组件的主题样式
  final KqPickerTitleConfig pickerTitleConfig;

  /// 点击【取消】回调给调用方的回调事件
  final Function()? onCancel;

  /// 日期选择模式，参考[KqDatePickerMode]，仅在[KqDateTimePickerMode.date]时生效
  final List<KqDatePickerMode>? dateModes;

  /// 默认日期选择模式，，仅在[KqDateTimePickerMode.date]时生效，不配置则默认取[dateModes]的第一个
  final KqDatePickerMode? defDateMode;

  /// 时间滚动选择时候的回调事件
  final Function(DateTime dateTime, List<int> selectedIndex)? onChange;

  /// 确认回调，return true 则代表关闭对话框，return false，则代表不关闭对话框
  final bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm;

  /// 确认回调，return true 则代表关闭对话框，return false，则代表不关闭对话框
  final bool Function(DateTime dateTime, List<int> selectedIndex,
      KqDatePickerMode? dateMode)? onConfirmWithMode;

  /// 自定义头部
  final List<Widget>? customHeaders;

  const KqDatePickerBottomSheet(
      {Key? key,
      this.minDateTime,
      this.maxDateTime,
      this.initialDateTime,
      this.dateFormat,
      this.leftBtnText,
      this.dateModes,
      this.defDateMode,
      this.rightBtnText,
      this.minuteDivider = 1,
      this.onCancel,
      this.onChange,
      this.onConfirm,
      this.onConfirmWithMode,
      this.customHeaders,
      this.pickerMode = KqDateTimePickerMode.date,
      this.pickerTitleConfig = KqPickerTitleConfig.Default})
      : super(key: key);

  @override
  KqDatePickerBottomSheetState createState() => KqDatePickerBottomSheetState();
}

class KqDatePickerBottomSheetState extends State<KqDatePickerBottomSheet> {
  KqDatePickerMode? selectDateMode;

  @override
  void initState() {
    super.initState();
    if (widget.defDateMode != null) {
      selectDateMode = widget.defDateMode;
    } else {
      if (widget.dateModes.isNotNullOrEmpty) {
        selectDateMode = widget.dateModes![0];
      } else {
        selectDateMode = KqDatePickerMode.byDay;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget? header;
    if (widget.dateModes.isNotNullOrEmpty) {
      var modes = widget.dateModes!;
      var initPos = 0;
      for (int i = 0; i < modes.length; i++) {
        var element = modes[i];
        if (element.name == selectDateMode?.name) {
          initPos = i;
        }
      }
      header = KqSelectTag(
        mode: KqSelectTagMode.wrap,
        wrapAlignment: WrapAlignment.start,
        bgPadding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 12.r),
        initPosition: initPos,
        tagList: modes.map((e) {
          return e == KqDatePickerMode.byDay
              ? KqIntl.currentResource.byDay
              : e == KqDatePickerMode.byMonth
                  ? KqIntl.currentResource.byMonth
                  : KqIntl.currentResource.byYear;
        }).toList(),
        onSelect: (index) {
          setState(() {
            selectDateMode = modes[index];
          });
        },
      );
    }

    Widget? pickerWidget;
    switch (widget.pickerMode) {
      case KqDateTimePickerMode.date:
        pickerWidget = KqDateWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: widget.customHeaders ?? (header == null ? null : [header]),
          initialDateTime: widget.initialDateTime,
          dateFormat: selectDateMode == KqDatePickerMode.byYear
              ? KqIntl.currentResource.yyyy
              : selectDateMode == KqDatePickerMode.byMonth
                  ? KqIntl.currentResource.yyyyMM
                  : KqIntl.currentResource.yyyyMMdd,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          onChange: widget.onChange,
          onConfirm: widget.onConfirmWithMode == null
              ? widget.onConfirm
              : (dateTime, selectedIndex) {
                  return widget.onConfirmWithMode!
                      .call(dateTime, selectedIndex, selectDateMode);
                },
          showBottomButton: false,
        );
        break;
      case KqDateTimePickerMode.time:
        pickerWidget = KqTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          initDateTime: widget.initialDateTime,
          dateFormat: widget.dateFormat,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          onChange: widget.onChange,
          onConfirm: widget.onConfirm,
          showBottomButton: false,
        );
        break;
      case KqDateTimePickerMode.datetime:
        pickerWidget = KqDateTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          initDateTime: widget.initialDateTime,
          dateFormat: widget.dateFormat,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          onChange: widget.onChange,
          onConfirm: widget.onConfirm,
          showBottomButton: false,
        );
        break;
    }

    return UnconstrainedBox(
        child: SizedBox(
            width: context.width,
            child: Material(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .radius ??
                            8.r),
                        topRight: Radius.circular(KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .radius ??
                            8.r))),
                color:
                    KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                        KqThemeColors.bgWhite,
                child: ClipRRect(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(KqThemeManager.instance
                              .getConfig()
                              .dialogConfig
                              .radius ??
                          8.r),
                      topRight: Radius.circular(KqThemeManager.instance
                              .getConfig()
                              .dialogConfig
                              .radius ??
                          8.r)),
                  child: pickerWidget,
                ))));
  }
}

enum KqDatePickerMode {
  /// 按日
  byDay,

  /// 按月
  byMonth,

  /// 按年
  byYear,
}

///时间选择模式枚举
enum KqDateTimePickerMode {
  /// Display DatePicker
  date,

  /// Display TimePicker
  time,

  /// Display DateTimePicker
  datetime,
}
